<template>
	<view class="zt-qd-con">

		<view v-if="isLoading">
			<uni-load-more status="loading"></uni-load-more>
		</view>
		<uni-popup ref="popup" type="center">服务器繁忙</uni-popup>

		<!-- 签到内容 -->
		<view class="qd-content">
			<view class="qd-item">
				<view class="bj">{{ signData.professionals + signData.gradeAndClass || '' }}</view>
				<view class="kc">课程：{{ signData.kec || ''  }}</view>
				<view class="kc-time">课程时间：{{ signData.keshi || ''  }}</view>
				<view class="fq-person">发起人：{{ signData.startUser || '' }}</view>
				<view class="qd-date">签到日：{{ signData.nowDate || ''  }}</view>
				<view class="qd-time">签到时间段：发起后20分钟</view>
				<view class="dd">地点：{{ signData.curAddress || ''  }}</view>
			</view>
			<view class="js-qi">
				距离结束还有：{{ signTime }}
			</view>
			<view :class="['qd-btn',signState === 1 ? 'active-qd-btn' : '']" @click="qdClick">
				<image src="/static/img/xiangji.png" class="qd-btn-bg"></image>
				{{ signState === 1 ? "点击签到" : "无签到任务" }}
			</view>
			<view 
			style="color: #007AFF;font-size:12px;text-align: center;cursor: pointer;margin-top: 10rpx;" 
			@click="lookScope">
				查看签到范围
			</view>
		</view>

		<message v-if="isMessage" :msgText="msgText"></message>
	</view>
</template>

<script>
	import loading from "./loading.vue"
	import Message from "./Message.vue"
	import uniPopup from "@/lib/components/uni-popup/uni-popup.vue";
	import io from "@/util/weapp.socket.io.js";
	import uniLoadMore from "@/lib/components/uni-load-more/uni-load-more.vue";
	import {
		isSignTime
	} from "@/util/isSignTime.js";
	import {
		getUserInfo
	} from "../network/users.js";
	export default {
		data() {
			return {
				timer: null,
				signTime: "",
				signState: 0,
				curIndex: 1,
				imgUrl: '',
				signData: {},
				isLoading: false,
				keshi: "无签到任务",
				nowDate: "",
				msgText: "",
				isMessage: false
			}
		},
		created() {

			let data = {};
			let v = uni.getStorageSync("isLogin");
			let vjiaose = uni.getStorageSync("jiaoses");
			getUserInfo({
				_id: v,
				jiaoses: vjiaose
			}).then(res => {
				data = res.data.data;

				//通过时间段 确定课时
				let timeInfo = isSignTime();
				if (timeInfo !== 0) {
					this.keshi = timeInfo.info;
				}

				//设置时间
				let n = new Date();
				let Y = n.getFullYear();
				let M = n.getMonth() + 1;
				let D = n.getDate();
				this.nowDate = Y + ":" + M + ":" + D;

				this.socketCorrelation(data);
			}).catch(err => {
				console.log("服务器繁忙！");
			})
		},

		methods: {
			popup() {
				this.$refs.popup.open();
				setTimeout(() => {
					this.$refs.popup.close();
				}, 2000)
			},

			tips(Text) {
				this.isMessage = true;
				this.msgText = Text
				setTimeout(() => {
					this.isMessage = false;
					this.isLoading = false;
				}, 2000);
			},

			socketCorrelation(data) {
				this.isLoading = true;

				//判断是否 有用户信息
				if (!data.username) {
					this.tips("请先填写详细信息")
					return;
				}

				/**
				 * socket 接收签到信息
				 */

				let socket = io('http://lovezt.free.idcfengye.com');
				this.socketID = socket.id;

				// 连接成功
				socket.on('connect', () => {
					socket.emit("message", {
						username: data.username,
						colleges: data.colleges, //学院
						professionals: data.professional, //专业
						gradeAndClass: data.gradeAndClassInfo, //年级和班级
						jiaoses: data.jiaoses, //角色
						schollNum: data.schollNum,
						keshi: this.keshi,
						nowDate: this.nowDate
					})

					this.isLoading = false;
				});

				socket.on('isSign', d => {
					if (d) {
						this.signData = d;
						this.signData.startUser = d.colleges + '(' + d.username + ')' + '(' + d.jiaoses + ')'
						this.isLoading = false;
						this.signState = 1;
						this.rockonTime(d.signTime);
					} else {
						this.signState = 0;
						this.isLoading = false;
					}
				})

				//正在连接
				socket.on('connecting', d => {
					console.log('正在连接', d);
				});

				// 连接错误   服务器发送错误
				socket.on('connect_error', d => {
					// this.popup()
					// return;
					console.log("连接错误   服务器发送错误");
				});

				// 连接超时
				socket.on('connect_timeout', d => {
					// this.popup()
					// return;
					console.log("连接超时");
				});

				// 断开连接
				socket.on('disconnect', reason => {
					console.log('断开连接', reason);
				});

				// 重新连接  服务器无错误后 自动重新连接
				socket.on('reconnect', attemptNumber => {
					console.log("重新连接  服务器无错误后 自动重新连接");
				});


				// 连接失败
				socket.on('reconnect_failed', () => {
					// this.popup()
					console.log("重新连接  服务器无错误后 自动重新连接");
				});


			},

			rockonTime(signTime) { //倒计时签到
				clearInterval(this.timer);

				let signD = new Date(signTime)
				let years = signD.getFullYear();
				let month = signD.getMonth() + 1;
				let day = signD.getDate();
				let hours = signD.getHours();
				let minutes = signD.getMinutes();
				let seconds = signD.getSeconds();

				let curD = new Date();
				let curYears = curD.getFullYear();
				let curMonth = curD.getMonth() + 1;
				let curDay = curD.getDate();
				let curHours = curD.getHours();
				let curMinutes = curD.getMinutes();
				let curSeconds = curD.getSeconds();

				//确保是当天 当个小时
				if (years === curYears && month === curMonth && day === curDay && hours === curHours) {
					if (curMinutes - minutes > 20) {
						this.signState = 0;
						return;
					}
					let ztM = 19 - (curMinutes - minutes); //分钟
					let ztS = 60 - curSeconds; //秒
					this.timer = setInterval(() => {
						if (ztM < 0) {
							clearInterval(this.timer)
						}
						if (ztS <= 0) {
							ztS = 60;
							ztM -= 1;
						}
						ztS -= 1;
						this.signTime = ztM + "分钟" + ztS + "秒"
					}, 1000)
				} else {
					this.signState = 0;
					return;
				}
			},

			qdClick() { //签到
				let that = this;
				
				if(JSON.stringify(that.signData) === "{}"){
					that.tips("无签到任务")
					return;
				}
				/**
				 * latitude: 29.7497760000,   //纬度
				   longitude: 107.2636250000, //经度
				 */
				uni.getLocation({ //获取位置
					type: 'gcj02',
					geocode: true,
					success: function(res) {
						
						 if (res.longitude > 107 || res.latitude > 29) {
								that.tips("不在签到范围内")
								return false;
						 } else{
						 	uni.chooseImage({ //在范围内可签到
						 		sizeType: ['original', 'compressed'],
						 		sourceType: ['camera'],
						 		success: function(res) {
						 			that.imgUrl = res.tempFilePaths[0]
						 		}
						 	});
						 }
					}
				});
			},

			lookScope() {
				uni.navigateTo({
					url: "../mapScope/mapScope" 
				})
			}

		},
		components: {
			uniLoadMore,
			uniPopup,
			loading,
			Message
		}
	}
</script>

<style>
	.qd-item {
		background: #FFFFFF;
		padding: 20rpx 20rpx;
		box-shadow: 0 0 9px #ccccc;
	}

	.bj {
		font-size: 14px;
		margin-bottom: 20rpx;
	}

	.dd,
	.kc,
	.kc-time,
	.fq-person,
	.qd-date,
	.qd-time {
		font-size: 12px;
		color: #CCCCCC;
		margin-top: 10rpx;
	}

	.js-qi {
		margin-left: 50%;
		transform: translateX(-50%);
		margin-top: 40rpx;
		height: 60rpx;
		width: 400rpx;
		border-radius: 30rpx;
		background: #009dff;
		line-height: 60rpx;
		text-align: center;
		font-size: 10px;
		color: #FFFFFF;
	}

	.qd-btn {
		width: 200rpx;
		height: 200rpx;
		border-radius: 50%;
		box-shadow: 0 0 9px #CCCCCC;
		background: #CCCCCC;
		font-size: 14px;
		text-align: center;
		color: #FFFFFF;
		margin-left: 50%;
		transform: translateX(-50%);
		margin-top: 220rpx;
	}

	.active-qd-btn {
		background: #009dff;
	}

	.qd-btn-bg {
		width: 100rpx;
		height: 70rpx;
		margin-left: 50%;
		transform: translateX(-50%);
		margin-top: 20rpx;
	}
</style>
